package com.xuyuan.spring.bean;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

//@Configuration
public class CustomBeanDefinitionConfig {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(CustomBeanDefinitionConfig.class);
        context.refresh();

        MyCustomBean myCustomBean = context.getBean(MyCustomBean.class);
        // 使用myCustomBean

        context.close();
    }

    @Bean
    public CustomBeanDefinitionRegistrar customBeanDefinitionRegistrar() {
        return new CustomBeanDefinitionRegistrar();
    }

    static class CustomBeanDefinitionRegistrar implements BeanDefinitionRegistryPostProcessor {

        @Override
        public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
            BeanDefinition beanDefinition = new RootBeanDefinition(MyCustomBean.class);
            registry.registerBeanDefinition("myCustomBean", beanDefinition);
        }

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            // 可以在这里进行其他BeanFactory的定制操作
        }
    }

    public static class MyCustomBean {
        // 自定义逻辑
    }
}